using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseRead.API.Applications.Commands.Popularizations;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Popularizations
{
    /// <summary>
    /// 获取疾病科普列表信息命令处理器
    /// </summary>
    public class GetPopularizationListCommandHandler : IRequestHandler<GetPopularizationListCommand, ApiPaging<List<PopularizationListDto>>>
    {
        /// <summary>
        /// 疾病科普仓储
        /// </summary>
        private readonly IBaseRepository<PopularScienceDiseaseModel> _popularizationRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<GetPopularizationListCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="popularizationRepository">疾病科普仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetPopularizationListCommandHandler(IBaseRepository<PopularScienceDiseaseModel> popularizationRepository, IMapper mapper, ILogger<GetPopularizationListCommandHandler> logger)
        {
            _popularizationRepository = popularizationRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取疾病科普列表命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiPaging<List<PopularizationListDto>>> Handle(GetPopularizationListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理疾病科普列表查询命令，页码：{PageIndex}，每页数量：{PageSize}", request.PageIndex, request.PageSize);

                // 构建查询
                var query = _popularizationRepository.GetAll().AsNoTracking();

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(request.PopularScienceTitle))
                {
                    query = query.Where(x => x.PopularScienceTitle.Contains(request.PopularScienceTitle));
                    _logger.LogDebug("应用标题搜索条件：{Title}", request.PopularScienceTitle);
                }

                if (!string.IsNullOrWhiteSpace(request.DiseaseType))
                {
                    query = query.Where(x => x.DiseaseType.Contains(request.DiseaseType));
                   
                }

                // 应用创建时间范围搜索条件
                if (request.StartTime.HasValue)
                {
                    query = query.Where(x => x.CreatedTime >= request.StartTime.Value);
                    _logger.LogDebug("应用开始时间搜索条件：{StartTime}", request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    // 将结束时间设置为当天的23:59:59，以包含整个结束日期
                    var endTime = request.EndTime.Value.Date.AddDays(1).AddSeconds(-1);
                    query = query.Where(x => x.CreatedTime <= endTime);
                    _logger.LogDebug("应用结束时间搜索条件：{EndTime}", endTime);
                }



                // 获取总数
                var totalCount = query.Count();
                _logger.LogDebug("查询到总记录数：{TotalCount}", totalCount);

                // 分页处理
                var skip = (request.PageIndex - 1) * request.PageSize;
                var popularizations = await query
                    .OrderByDescending(x => x.CreatedTime)
                    .Skip(skip)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                _logger.LogDebug("分页查询完成，当前页记录数：{Count}", popularizations.Count);

                // 映射到DTO
                var popularizationDtos = _mapper.Map<List<PopularizationListDto>>(popularizations);

                // 计算分页信息
                var totalPages = (int)Math.Ceiling((double)totalCount / request.PageSize);


                _logger.LogInformation("疾病科普列表查询完成，总数：{TotalCount}，当前页：{PageIndex}，总页数：{TotalPages}",
                    totalCount, request.PageIndex, totalPages);

                return new ApiPaging<List<PopularizationListDto>>
                {
                    code = ResultEnumCode.Ok,
                    message = "疾病科普列表查询成功",
                    data = popularizationDtos,
                    TotalCount = totalCount,
                    PageCount = totalPages,

                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "疾病科普列表查询过程中发生异常");
                return new ApiPaging<List<PopularizationListDto>>
                {
                    code = ResultEnumCode.fails,
                    message = $"疾病科普列表查询异常：{ex.Message}",
                    data = new List<PopularizationListDto>(),
                    PageCount = 0,
                    TotalCount = 0,

                };
            }
        }
    }
}